//
//  RegisterViewController.m
//  LiveStar
//
//  Created by SKT1 on 2016/12/7.
//  Copyright © 2016年 apple. All rights reserved.
//

#import "RegisterViewController.h"
#import "RegisterSuccessViewController.h"
#import "LoginViewController.h"

@interface RegisterViewController ()<UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITextField *PhoneNumTextField;
@property (weak, nonatomic) IBOutlet UITextField *VcodeTextField;
@property (weak, nonatomic) IBOutlet UIButton *GetCodeBtn;
@property (weak, nonatomic) IBOutlet UITextField *PasswordTextField;
@property (weak, nonatomic) IBOutlet UITextField *repeatPasswordTextField;
@property (weak, nonatomic) IBOutlet UIButton *RegisterBtn;
@property (weak, nonatomic) IBOutlet UIButton *lookPWDBtn_One;

@property (weak, nonatomic) IBOutlet UIButton *lookPWDBtn_Second;

/**
   记录当前密码显示状态 默认为no
 */
@property (nonatomic, assign) BOOL firstState;
@property (nonatomic, assign) BOOL secondState;
@end

@implementation RegisterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setNav];
    
    [self setUpOptions];

}

- (void)setNav {
    
    if ([self.is_Sign isEqualToString:@"1"]) {
        self.navigationItem.title = @"手机注册";
        [self.RegisterBtn setTitle:@"注册" forState:UIControlStateNormal];
    } else {
        self.navigationItem.title = @"忘记密码";
                [self.RegisterBtn setTitle:@"确认" forState:UIControlStateNormal];
    }

}

#pragma mark --  设置
- (void)setUpOptions {
    self.firstState = NO;
    self.secondState = NO;
    self.PasswordTextField.secureTextEntry = YES;
    self.repeatPasswordTextField.secureTextEntry = YES;
    self.PhoneNumTextField.keyboardType = UIKeyboardTypePhonePad;
    self.VcodeTextField.keyboardType = UIKeyboardTypePhonePad;
    self.PasswordTextField.keyboardType = UIKeyboardTypeDefault;
    
    kButtonRadius(self.RegisterBtn, 35/2);
    self.RegisterBtn.titleEdgeInsets = UIEdgeInsetsMake(-12, 0, 0, 0);
    kButtonRadius(self.GetCodeBtn, 5);
    self.GetCodeBtn.backgroundColor = [UIColor mainColor];
    
}
#pragma mark -- 获取验证码
- (IBAction)getVerificationCode:(id)sender {
    NSString *phoneNum = self.PhoneNumTextField.text;
    //首先判断输入的手机号
    if ([self isValidateMobile:phoneNum]&&[self phoneNumDigitsisAvailableWithPhoneNum:phoneNum]) {
        [self getCodeWithPhoneNum:phoneNum];
    } else {
        //输入正确的手机号
        [self showTitle:@"您输入的手机号不正确!"];
//        [self showHUDInView:self.view title:nil];
    }
    //通过手机号发送验证码
}

//判断手机号位数 以及是可用
- (BOOL)phoneNumDigitsisAvailableWithPhoneNum:(NSString *)phoneNum {
    if (phoneNum.length == 11) {
        return YES;
    } else {
        return NO;
    }
    
}
-(BOOL)isValidateMobile:(NSString *)phoneNum
{
    //手机号以13， 15，18开头，八个 \d 数字字符
    NSString *phoneRegex = @"^((17[0-9])|(13[0-9])|(15[^4,\\D])|(18[0,0-9]))\\d{8}$";
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
    //    NSLog(@"phoneTest is %@",phoneTest);
    return [phoneTest evaluateWithObject:phoneNum];
}
#pragma mark -- 获取验证码
- (void)getCodeWithPhoneNum:(NSString *)phoneNum {
    [self startTimer];
    NSDictionary *dict = @{@"phone":phoneNum};
    NSString *urlString = [TEST_URL stringByAppendingString:kGetVCode];
    [self showHUDInView:self.view title:nil];
    [NetworkTools postReqeustWithParams:dict UrlString:urlString successBlock:^(id responseObject) {
        if ([KString(responseObject[@"code"]) isEqualToString:@"200"]) {
            [self showTitle:responseObject[@"data"][@"message"]];
        } else {
            [self showTitle:@"获取验证码失败"];
        }
        [self hideHUD];
    } failureBlock:^(NSError *error) {
        [self hideHUD];
    } showHUD:NO];
}

#pragma mark -- 开启定时器
- (void)startTimer {
   
    __block NSInteger time = 59; //倒计时时间
    
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    
    dispatch_source_set_event_handler(_timer, ^{
        
        if(time <= 0){ //倒计时结束，关闭
            
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置按钮的样式
                [self.GetCodeBtn setTitle:@"重新发送" forState:UIControlStateNormal];
                self.GetCodeBtn.titleLabel.font = UIFont(11);
                [self.GetCodeBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
                self.GetCodeBtn.userInteractionEnabled = YES;
            });
        }else{
            
            int seconds = time % 60;
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置按钮显示读秒效果
                [self.GetCodeBtn setTitle:[NSString stringWithFormat:@"%ds", seconds] forState:UIControlStateNormal];
                [self.GetCodeBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                self.GetCodeBtn.userInteractionEnabled = NO;
            });
            time--;
        }
    });
    dispatch_resume(_timer);

}

#pragma mark -- 注册 / 修改密码
- (IBAction)Register:(id)sender {
    //验证手机号 验证码 密码 发送请求
    NSString *mobileNum = self.PhoneNumTextField.text;
    NSString *Vcode = self.VcodeTextField.text;
    NSString *password = self.PasswordTextField.text;
    NSString *repeatPassword = self.repeatPasswordTextField.text;
    if ([mobileNum isEqualToString:@""]
        ||[repeatPassword isEqualToString:@""]||[Vcode isEqualToString:@""]||[password isEqualToString:@""]) {
        [self showTitle:@"请完善信息..."];
    }
    if ([self verifyPasswordWithPassword:password RepeatPassword:repeatPassword]) {
        //提交
        if ([self.is_Sign isEqualToString:@"1"]) {//注册
            [self ResgistRequestWithPhoneNum:mobileNum Password:password VCode:Vcode];
        } else {//修改密码
            [self ResivePWDRequestWithPhoneNum:mobileNum Password:password VCode:Vcode];
        }
    } else {
        [self showTitle:@"密码输入不一致,请重新输入!"];
    }
}

//验证输入的密码是否一致(6位以上)
- (BOOL)verifyPasswordWithPassword:(NSString *)password RepeatPassword:(NSString *)rppassword {
    if ([password isEqualToString:rppassword]) {
        return YES;
    } else {
        return NO;
    }
    
}

// 手机号注册请求
- (void)ResgistRequestWithPhoneNum:(NSString *)phoneNum Password:(NSString *)password VCode:(NSString *)code {
    NSDictionary *dict = @{
                           @"phone":phoneNum,
                           @"password":password,
                           @"code":code
                           };
    NSString *urlString = [TEST_URL stringByAppendingString:kRegist_Phone];
    [NetworkTools postReqeustWithParams:dict UrlString:urlString successBlock:^(id responseObject) {
//        RegisterSuccessViewController *registerSuccessVC = [RegisterSuccessViewController new];
//        [self.navigationController pushViewController:registerSuccessVC animated:YES];
    } failureBlock:^(NSError *error) {
        [self showTitle:@"链接服务器失败..."];
    } showHUD:NO];
}

//修改密码请求
- (void)ResivePWDRequestWithPhoneNum:(NSString *)phoneNum Password:(NSString *)password VCode:(NSString *)code {
    NSDictionary *dict = @{
                           @"phone":phoneNum,
                           @"password":password,
                           @"code":code
                           };
    NSString *urlString = [TEST_URL stringByAppendingString:kGetPassWord];
    [NetworkTools postReqeustWithParams:dict UrlString:urlString successBlock:^(id responseObject) {
        UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:@"提示" message:@"错误" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            LoginViewController *loginVc = [LoginViewController new];
            [self.navigationController pushViewController:loginVc animated:YES];
        }];
        [alertVc addAction:action];
        [self presentViewController:alertVc animated:YES completion:nil];
        
    } failureBlock:^(NSError *error) {
        
    } showHUD:NO];
}




#pragma mark -- UITextField Delegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    return YES;
}


#pragma mark -- 查看密码
- (IBAction)lookPassWord:(id)sender {
    if (sender == self.lookPWDBtn_One) {
        self.firstState = !self.firstState;
        if (self.firstState) {
            [sender setImage:[UIImage imageNamed:@"PasswordYES"] forState:UIControlStateNormal];
            self.PasswordTextField.secureTextEntry = NO;
        } else {
            [sender setImage:[UIImage imageNamed:@"PasswordNO"] forState:UIControlStateNormal];
            self.PasswordTextField.secureTextEntry = YES;
        }
    } else {
        self.secondState = !self.secondState;
        if (self.secondState) {
            [sender setImage:[UIImage imageNamed:@"PasswordYES"] forState:UIControlStateNormal];
            self.repeatPasswordTextField.secureTextEntry = NO;
        } else {
            [sender setImage:[UIImage imageNamed:@"PasswordNO"] forState:UIControlStateNormal];
            self.repeatPasswordTextField.secureTextEntry = YES;
        }

    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
